//
//  ViewController.m
//  iceTearsTest
//
//  Created by 张飞跃 on 16/4/25.
//  Copyright © 2016年 张飞跃. All rights reserved.
//

#import "ViewController.h"
#import "IPAdress.h"
#import "WebVIewVC.h"
#import "ZFYKeychain.h"
#import "BgView.h"
#import <ReactiveCocoa/ReactiveCocoa.h> 

@interface ViewController ()
{
    BgView *view1;
}
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //[self RelativeTime];
    
//    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
//    image.image = [UIImage imageNamed:@"start-568h@2x"];
//    image.transform = CGAffineTransformMakeScale(1,0.99);
//    [self.view addSubview:image];
   // [self example0];
    
    [self example1];
    
//    UIButton *Btn = [[UIButton  alloc]initWithFrame:CGRectMake(100, 130, 50, 30)];
//    [Btn setTitle:@"展示" forState:UIControlStateNormal];
//    Btn.backgroundColor = [UIColor redColor];
//    [self.view addSubview:Btn];
//    [[Btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
//        NSLog(@"btnbtnbtn");
//        [self example2];
//
//        
//    }];

    
}
- (void)example2{
    if (!view1) {
        //加载view的试图
        view1 = [[BgView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        view1.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        view1.delegate = self;
        UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
        [currentWindow addSubview:view1];

    }
   
}
-(void)deleteView:(NSString *)type
{
    NSLog(@"11");
    if ([type isEqualToString:@"1"]) {
        [view1 removeFromSuperview];
        view1 = nil;
    }
    
}
- (void)example1{
    
    
    
    UITextField *usernameTextField = [[UITextField alloc]initWithFrame:CGRectMake(60, 64, 300, 50)];
    [self.view addSubview:usernameTextField];
    usernameTextField.borderStyle = UITextBorderStyleLine;
    
    [usernameTextField.rac_textSignal subscribeNext:^(id x){
        NSLog(@"%@", x);
    }];
//    
//    [[usernameTextField.rac_textSignal
//      filter:^BOOL(id value){
//          NSString*text = value;
//          return text.length > 3;
//      }]
//     subscribeNext:^(id x){
//         NSLog(@"2-%@", x);
//     }];
//    
//    [[[usernameTextField.rac_textSignal
//       map:^id(NSString*text){
//           return @(text.length); 
//       }]
//      filter:^BOOL(NSNumber*length){
//          return[length integerValue] > 3;
//      }]
//     subscribeNext:^(id x){
//         NSLog(@"3-%@", x);
//     }];
//    
//    RACSignal *validUsernameSignal =
//    [usernameTextField.rac_textSignal
//     map:^id(NSString *text) {
//         return @(text.length>3);
//     }];
//    
//    RAC(usernameTextField, backgroundColor) =
//    [validUsernameSignal
//     map:^id(NSNumber *passwordValid){
//         return[passwordValid boolValue] ? [UIColor clearColor]:[UIColor yellowColor];
//     }];
    
    UIButton *Btn = [[UIButton  alloc]initWithFrame:CGRectMake(100, 130, 50, 30)];
    Btn.backgroundColor = [UIColor redColor];
    [self.view addSubview:Btn];
    [[Btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        NSLog(@"btnbtnbtn");
        
        [ZFYKeychain savePassWord:usernameTextField.text forKey:@"aaa"];
        NSLog(@"%@", [ZFYKeychain readPassWordObjectForKey:@"aaa"]);
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(60, 200, 200, 30)];
        label.text = [ZFYKeychain readPassWordObjectForKey:@"aaa"];
        label.font = [UIFont systemFontOfSize:14];
        [label setTextColor:[UIColor redColor]];
        [self.view addSubview:label];
        
    }];
    

    
}

- (void)example0{
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",nil];
    //初始化UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    segmentedControl.frame = CGRectMake(20.0, 100.0, 250.0, 50.0);
    segmentedControl.selectedSegmentIndex = 2;//设置默认选择项索引
    segmentedControl.tintColor = [UIColor redColor];
    segmentedControl.layer.cornerRadius = 10;
    segmentedControl.layer.masksToBounds = YES;
    //    segmentedControl.layer.borderColor = [UIColor whiteColor].CGColor;
    //    segmentedControl.layer.borderWidth = 3;
    [self.view addSubview:segmentedControl];
    
    NSLog(@"%@",[self replaceUnicode:@"\u5f20\u4e09"]);
    NSLog(@"%@",[self utf8ToUnicode:@"张三"]);
    
    /*@property(nonatomic,readonly)        CGFloat   ascender;
    @property(nonatomic,readonly)        CGFloat   descender;
    @property(nonatomic,readonly)        CGFloat   capHeight;
    @property(nonatomic,readonly)        CGFloat   xHeight;
    @property(nonatomic,readonly)        CGFloat   lineHeight NS_AVAILABLE_IOS(4_0);
     */
    NSInteger n = 6;//最多显示的行数
    NSString * labelStr = @"你好，这是UILabel的自";
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 160, 200, 14)];
    label.font = [UIFont systemFontOfSize:11];
    label.backgroundColor = [UIColor orangeColor];
    label.text = labelStr;
    label.numberOfLines = 0;
    [self.view addSubview:label];
    
    CGSize labelSize = {0, 0};
    
    labelSize = [self ZFYtextHeightFromTextString:labelStr width:label.frame.size.width fontSize:label.font.pointSize];
    
    NSLog(@"%f",label.font.pointSize);//label的字体大小
    NSLog(@"%f",label.font.lineHeight);//label的行高
    NSLog(@"%f",labelSize.height);//label计算行高
  

    
    CGFloat rate = label.font.lineHeight; //每一行需要的高度
    NSLog(@"%f",rate);
    CGRect frame= label.frame;
    if (labelSize.height>rate*n) {
        frame.size.height = rate*n;
    }else{
        frame.size.height = labelSize.height;
    }
    label.frame = frame;
    

}
-(CGSize)ZFYtextHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{
    //计算 label需要的宽度和高度
    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
    CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    
     CGSize size1 = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:size]}];
    
    return CGSizeMake(size1.width, rect.size.height);
}
- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    //张三  \u5f20\u4e09

    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
  //  NSLog(@"Output = %@", returnStr);
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

-(NSString *) utf8ToUnicode:(NSString *)string{
    
    NSUInteger length = [string length];
    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++){
        unichar _char = [string characterAtIndex:i];
        //判断是否为英文和数字
        if (_char <= '9' && _char >='0'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='a' && _char <= 'z'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='A' && _char <= 'Z')
        {
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else{
            [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
        }
    }
    return s;
}

//获取相对时间
- (void)RelativeTime {
    NSDateComponents * components = [[NSDateComponents alloc] init];
    components.month = -2;
    //    components.day = 10;
    //    components.hour = 10;
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    NSDate * currentDate = [NSDate date];
    NSDate * nextData = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    
    formatter.dateFormat = @"yyyy年MM月dd日HH时mm分ss秒";
    NSString * str = [formatter stringFromDate:nextData];
    NSLog(@"%@",str);

}
- (void)createIPAddress{
    [self ipip1];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    UIButton  *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 64, 50, 30)];
    btn.backgroundColor = [UIColor greenColor];
    [btn addTarget:self action:@selector(Click) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"跳转" forState:UIControlStateNormal];;
    [self.view addSubview:btn];
    
    NSString* ip_iphone = [self deviceIPAdress];
    NSLog(@"ip:%@",ip_iphone);
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 90, 200, 30)];
    label.textColor = [UIColor redColor];
    label.text = ip_iphone;
    [self.view addSubview:label];
    
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(50, 180, 200, 80)];
    label2.textColor = [UIColor orangeColor];
    label2.numberOfLines = 0;
    label2.text = [self whatismyipdotcom];
    [self.view addSubview:label2];

}

- (NSString *)deviceIPAdress {
    InitAddresses();
    GetIPAddresses();
    GetHWAddresses();
//     NSLog(@"hw_addrs:%s",hw_addrs[1]);//物理地址

    return [NSString stringWithFormat:@"%s", ip_names[1]];
}
- (void)Click{
    NSLog(@"跳转");
    WebVIewVC *web = [[WebVIewVC alloc]init];
    [self.navigationController pushViewController:web animated:YES];

}

- (void)ipip1

{
    NSLog(@"111");
    
    NSURL *url = [NSURL URLWithString:@"http://fw.qq.com/ipaddress"];
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:@"post"];
    
    [request setTimeoutInterval:8.0f];
    
    NSHTTPURLResponse *response;
    
    
    
    //返回的是GBK编码
    
    //NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:@""responseerror:nil];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSLog(@"%ld",[response statusCode]);
    if (200 == [response statusCode]) {
        
        //直接转,将会产生乱码或者字符串为空    NSUTF8StringEncoding
        
        NSString *temp1 = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
        
        //                               NSASCIIStringEncoding
        
        NSString *temp2 = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
        
        NSLog(@"---------temp1---%@",temp1);
        
        NSLog(@"---------temp2---%@",temp2);
        
        NSLog(@"-------------------------------------");
        
        
        
        // 一、 GBK编码 (通过CFStringCreateWithBytes转码)
        
        
        CFStringRef GBKCFstirng =CFStringCreateWithBytes(NULL,[returnData bytes], [returnData length],kCFStringEncodingGB_18030_2000,false);
        
        
        
        //  NSString *gbkNSString1 = (NSString *)GBKCFStirng;
        NSString *gbkNSString1 = (__bridge NSString *)GBKCFstirng;
        NSLog(@"--gbkNSString1---%@",gbkNSString1);
        
        
        
        // 二、 GBK编码 (通过CFStringConvertEncodingToNSStringEncoding转码)
        
        NSStringEncoding nsEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        NSString *gbkNSString2 = [[NSString alloc] initWithData:returnData encoding:nsEncoding];
        
        NSLog(@"--gbkNSString2---%@",gbkNSString2);
        
        
        
        NSLog(@"-------------------------------------");
        
        
        
        //转成NSUTF8StringEncoding的字符串
        
        NSData *tempdata = [gbkNSString1 dataUsingEncoding:NSUTF8StringEncoding];
        
        NSString *UTF8_NSString = [[NSString alloc] initWithData:tempdata
                                                        encoding:NSUTF8StringEncoding];
        
        NSLog(@"--UTF8_NSString--%@",UTF8_NSString);
        
    }
    
}
//- (void)getCurrentIP
//{
//       NSURL *url = [NSURL URLWithString:@"http://automation.whatismyip.com/n09230945.asp"];
//    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//    [request setCompletionBlock:^{
//            NSString *responseString = [request responseString];
//               if (responseString) {
//    
//                    NSString *ip = [NSString stringWithFormat:@"%@", responseString];
//    
//                    NSLog(@"responseString = %@", ip);
//                };
//    
//           }];
//    
//        [request setFailedBlock:^{
//             }];
//}
- (NSString *) whatismyipdotcom
{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://fw.qq.com/ipaddress "];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:1 error:&error];
    return ip ? ip : [error localizedDescription];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
